package com.taijihuabao.common.activititasklistener.quittasklistener;

import com.alibaba.excel.util.CollectionUtils;
import com.taijihuabao.modules.entity.ApprovalEntity;
import com.taijihuabao.modules.entity.ApprovalHistoryEntity;
import com.taijihuabao.modules.entity.DeptUserEntity;
import com.taijihuabao.modules.mapper.ApprovalHistoryMapper;
import com.taijihuabao.modules.mapper.ApprovalMapper;
import com.taijihuabao.modules.mapper.DeptUserMapper;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.task.IdentityLink;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 给单个任务赋审批人
 * @author wang
 */
@Component
public class ThisDeptListener implements TaskListener {

    @Resource
    private ApprovalMapper approvalMapper;
    @Resource
    private DeptUserMapper deptUserMapper;
    @Resource
    private ApprovalHistoryMapper approvalHistoryMapper;

    /**
     * 主管
     */
    private final String ADMIN = "administrator";
    /**
     * 审核员
     */
    private final String ASSESSOR = "assessor";
    /**
     * 考勤专员
     */
    private final String CHECK = "attendanceCommissioner";
    /**
     * 人事专员
     */
    private final String PERSON ="personnelCommissioner";
    /**
     * 总务部
     */
    private final String GENERAL = "generalMangener";
    /**
     * 人事部
     */
    private final String PERSON_DEPT = "personnelDept";

    @Override
    public void notify(DelegateTask delegateTask) {
        //审批id
        String businessKey = delegateTask.getExecution().getProcessInstanceBusinessKey();
        //查询审批单
       ApprovalEntity approvalEntity = approvalMapper.selectById(Long.valueOf(businessKey));
        //查询部门所有人
        List<DeptUserEntity> applies = deptUserMapper.selectDeptByUserId(approvalEntity.getApplyUserId());
        String dept = applies.get(0).getDeptCode();
        List<DeptUserEntity> deptUserEntities = deptUserMapper.selectDeptByDeptCode(dept);
        //根据部门和id查询角色
        for(DeptUserEntity due : deptUserEntities){
            if (ADMIN.equals(due.getDeptRole()) || ASSESSOR.equals(due.getDeptRole())) {
                delegateTask.addCandidateUser(String.valueOf(due.getUserId()));
            }
        }
        Set<IdentityLink> users = delegateTask.getCandidates();
        if(CollectionUtils.isEmpty(users)){
            delegateTask.addCandidateUser(String.valueOf(approvalEntity.getApplyUserId()));
        }

        ApprovalHistoryEntity approvalHistoryEntity = AddHistoryUtil.addHistory(delegateTask, approvalEntity, dept);
        approvalHistoryMapper.insertApproval(approvalHistoryEntity);
    }
}
